/************************************
 * Package: RGcpp					*
 * Authors: Rui Eduardo Gouveia Gil	*
 * Date: 2010						*
 ************************************/
#include "rgcpp/tools/Encoder.h"

namespace rgcpp
{

bool Encoder::init=false;
Map<std::string,char> Encoder::decodeMap;
Map<char,std::string> Encoder::encodeMap;

std::string Encoder::decode(const std::string& request)
{
	Encoder::initMaps();

	std::string mathStr;
	std::ostringstream stream;

	for(std::string::const_iterator i=request.begin(); i!=request.end(); i++)
	{
		if(*i == '%')
		{
			mathStr = *i;
			i++;
			mathStr += *i;
			i++;
			mathStr += *i;

			stream << Encoder::decodeMap[mathStr];
		}
		else
			stream << *i;
	}

	std::string result = stream.str();
	return result;
}

std::string Encoder::encode(const std::string& response)
{
	Encoder::initMaps();

	std::ostringstream stream;

	for(std::string::const_iterator i=response.begin(); i!=response.end(); i++)
	{
		if(Encoder::encodeMap.find(*i) != Encoder::encodeMap.end())
			stream << Encoder::encodeMap[*i];
		else
			stream << *i;
	}

	std::string result = stream.str();
	return result;
}

void Encoder::initMaps()
{
	if(Encoder::init)
		return;

	Encoder::encodeMap['$'] = "%24";
	Encoder::encodeMap['&'] = "%26";
	Encoder::encodeMap['+'] = "%2B";
	Encoder::encodeMap[','] = "%2C";
	Encoder::encodeMap['/'] = "%2F";
	Encoder::encodeMap[':'] = "%3A";
	Encoder::encodeMap[';'] = "%3B";
	Encoder::encodeMap['='] = "%3D";
	Encoder::encodeMap['?'] = "%3F";
	Encoder::encodeMap['@'] = "%40";
	Encoder::encodeMap[' '] = "%20";
	Encoder::encodeMap['\"'] ="%22";
	Encoder::encodeMap['<'] = "%3C";
	Encoder::encodeMap['>'] = "%3E";
	Encoder::encodeMap['#'] = "%23";
	Encoder::encodeMap['%'] = "%25";
	Encoder::encodeMap['{'] = "%7B";
	Encoder::encodeMap['}'] = "%7D";
	Encoder::encodeMap['|'] = "%7C";
	Encoder::encodeMap['\\'] ="%5C";
	Encoder::encodeMap['^'] = "%5E";
	Encoder::encodeMap['~'] = "%7E";
	Encoder::encodeMap['['] = "%5B";
	Encoder::encodeMap[']'] = "%5D";
	Encoder::encodeMap['`'] = "%60";

	Encoder::decodeMap["%24"] = '$';
	Encoder::decodeMap["%26"] = '&';
	Encoder::decodeMap["%2B"] = '+';
	Encoder::decodeMap["%2C"] = ',';
	Encoder::decodeMap["%2F"] = '/';
	Encoder::decodeMap["%3A"] = ':';
	Encoder::decodeMap["%3B"] = ';';
	Encoder::decodeMap["%3D"] = '=';
	Encoder::decodeMap["%3F"] = '?';
	Encoder::decodeMap["%40"] = '@';
	Encoder::decodeMap["%20"] = ' ';
	Encoder::decodeMap["%22"] ='\"';
	Encoder::decodeMap["%3C"] = '<';
	Encoder::decodeMap["%3E"] = '>';
	Encoder::decodeMap["%23"] = '#';
	Encoder::decodeMap["%25"] = '%';
	Encoder::decodeMap["%7B"] = '{';
	Encoder::decodeMap["%7D"] = '}';
	Encoder::decodeMap["%7C"] = '|';
	Encoder::decodeMap["%5C"] = '\\';
	Encoder::decodeMap["%5E"] = '^';
	Encoder::decodeMap["%7E"] = '~';
	Encoder::decodeMap["%5B"] = '=';
	Encoder::decodeMap["%5D"] = ']';
	Encoder::decodeMap["%60"] = '`';

	Encoder::init = true;
}

}
